// https://leetcode-cn.com/problems/delete-node-in-a-bst/
// 450. 删除二叉搜索树中的节点

#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <queue>
#include <limits.h>

using namespace std;

// struct ListNode {
//     int val;
//     ListNode *next;
//     ListNode() : val(0), next(nullptr) {}
//     ListNode(int x) : val(x), next(nullptr) {}
//     ListNode(int x, ListNode *next) : val(x), next(next) {}
// };

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};




class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if (root == nullptr) return root;
        
        if (root->val == key) {
            if (root->left == nullptr) return root->right;
            else if (root->right == nullptr) return root->left;
            else {
                TreeNode *cur = root->right;
                while (cur->left != nullptr)
                    cur = cur->left;
                cur->left = root->left;
                TreeNode *tmp = root;
                root = root->right;
                delete tmp;

                return root;
            }  
        }
        if (root->val > key) root->left = deleteNode(root->left, key);
        if (root->val < key) root->right = deleteNode(root->right, key);
        return root;
    }
};



int main() {
    Solution obj = Solution();
}